package com.maiji.cloud.controller;

import com.maiji.cloud.entities.manager.Menu;
import com.maiji.cloud.entities.manager.Role;
import com.maiji.cloud.entities.manager.User;
import com.maiji.cloud.response.BaseDataResDto;
import com.maiji.cloud.response.BaseOutPutDto;
import com.maiji.cloud.response.Status;
import com.maiji.cloud.service.MenuService;
import com.maiji.cloud.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;

/**
 * 这是一个只要登录就能访问的Controller
 * 主要用来获取一些配置信息
 */
@RestController
@RequestMapping("/config")
public class ConfigController {

    private static final String REST_URL_APPLOGIN = "http://MAIJICLOUD-APPLOGIN";
    @Value("${communityManagerIds}")
    private String communityManagerIds;
    @Autowired
    MenuService menuService;
    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/sysmenu")
    public BaseDataResDto<List<Menu>> sysmenu() {
        List<Menu> menuList = menuService.findAllMenusByUserId();
        return new BaseDataResDto<List<Menu>>(Status.SUCCESS).setData(menuList);
    }

    @RequestMapping("/user")
    public User currentUser() {
        return UserUtil.getCurrentUser();
    }

    @GetMapping("/getMaijiAppOfficialToken")
    public BaseOutPutDto<String> getMaijiAppOfficialToken(){
        User currentUser = UserUtil.getCurrentUser();
        List<Role> roles = currentUser.getRoles();
        Boolean anyMatch = roles.parallelStream().anyMatch(role -> Arrays.asList(communityManagerIds.split(";")).contains(role.getUuId()));
        if (! anyMatch) return new BaseOutPutDto<>(Status.PERMISSIONDENIED);
        return restTemplate.getForObject(REST_URL_APPLOGIN+ "/getMaijiAppOfficialToken", BaseOutPutDto.class);
    }

}
